package cn.gigi.ipspringbootstarter.service;

import cn.gigi.ipspringbootstarter.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class IpCountService {

    // 用于存储 IP 访问次数
    private Map<String, Integer> ipCountMap = new HashMap<>();

    // 使用 ip-starter 的第三方项目，会声明 HttpServletRequest bean，此处可以直接注入
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IpProperties ipProperties;

    /**
     * 统计 IP 访问次数
     */
    public void count() {
        String ip = request.getRemoteAddr();
        Integer count = ipCountMap.get(ip);
        ipCountMap.put(ip, count == null ? 1 : count + 1);
    }

    /**
     * 打印 IP 访问次数
     */
    @Scheduled(cron = "0/#{ipProperties.cycle} * * * * ?") // 每5秒执行一次
    public void print() {
        if(IpProperties.Model.DETAIL.getValue().equals(ipProperties.getModel())){
            System.out.println("~~~~~~~~~~ IP访问监控(detail) ~~~~~~~~~~");
            System.out.println("+--------ip-address---------|---num---+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println(String.format("|%25s  |%7d  |", key, value));
            }
            System.out.println("+---------------------------|---------+");

        }else if(IpProperties.Model.SIMPLE.getValue().equals(ipProperties.getModel())){
            System.out.println("~~~~~ IP访问监控(simple) ~~~~~");
            System.out.println("+---------ip-address--------+");
            for (String key : ipCountMap.keySet()) {
                System.out.println(String.format("|%25s  |", key));
            }
            System.out.println("+---------------------------+");
        }

        if (ipProperties.getReset()) {
            ipCountMap.clear();
        }
    }

}
